package com.zhou.base.resilience4j.test.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.base.resilience4j.test.constant.SystemConstant;
import com.zhou.base.resilience4j.test.entity.ImportStudent;
import com.zhou.base.resilience4j.test.handler.ExcelVerifyStudentHandlerImpl;
import com.zhou.base.resilience4j.test.mapper.programmer.ImportStudentMapper;
import com.zhou.base.resilience4j.test.model.middle.ExcelVerifyImportStudentEntity;
import com.zhou.base.resilience4j.test.service.IImportStudentService;
import com.zhou.base.resilience4j.test.util.BeanUtil;
import com.zhou.common.base.mq.exception.BizException;
import com.zhou.common.base.mq.model.ExcelResVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 导入学生信息 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2022-08-12
 */
@Transactional(rollbackFor = {})
@Service
public class ImportStudentServiceImpl extends ServiceImpl<ImportStudentMapper, ImportStudent> implements IImportStudentService {

    @Qualifier("jsonRedisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public ExcelResVo importPreview(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        //校验表头
        params.setImportFields(new String[]{"学生姓名", "证件号", "毕业院校"});
        //校验实体类上的注解
        params.setNeedVerify(true);
        //校验当前文件中重复的数据
        params.setVerifyHandler(new ExcelVerifyStudentHandlerImpl());
        ExcelImportResult<ExcelVerifyImportStudentEntity> importResult = ExcelImportUtil.importExcelMore(file.getInputStream(),
                ExcelVerifyImportStudentEntity.class, params);

        List<ExcelVerifyImportStudentEntity> list = importResult.getList();
        List<ExcelVerifyImportStudentEntity> successList = importResult.getList();

        //1.校验学校是否在库中

        //2.校验学校是否已经在库中

        //3.校验学信网毕业学校是否一致，并使用学信网的毕业事件

        List successList1 = successList.stream()
                .sorted(Comparator.comparing(ExcelVerifyImportStudentEntity::getId)).collect(Collectors.toList());
        List failList = importResult.getFailList().stream()
                .sorted(Comparator.comparing(ExcelVerifyImportStudentEntity::getId)).collect(Collectors.toList());

        ExcelResVo<ExcelVerifyImportStudentEntity> resVo = new ExcelResVo<ExcelVerifyImportStudentEntity>();
        resVo.setFailList(failList);
        resVo.setSuccessList(successList1);
        resVo.setTotalCount(successList1.size() + failList.size());
        if (successList1.size() > 0) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            redisTemplate.opsForValue().set(SystemConstant.EXCEL_IMPORT_REDIS_KEY + uuid, successList1, 1800, TimeUnit.SECONDS);
            resVo.setSeriId(uuid);
        }
        return resVo;
    }

    @Override
    public void importExcel(String seriId) {
        List<ExcelVerifyImportStudentEntity> lists =
                (List<ExcelVerifyImportStudentEntity>) redisTemplate.opsForValue().get(SystemConstant.EXCEL_IMPORT_REDIS_KEY + seriId);
        if (lists == null) {
            throw new BizException(9999, "序列化id不存在");
        }
        //4.插入数据库
        List<ImportStudent> importStudents = BeanUtil.copyList(lists, ImportStudent.class);
        //做一些处理
        /*SysUserInfo user = SecurityContext.getUser();
        importStudents.forEach(t -> {
            t.setCreator(StringUtils.isNotEmpty(user.getName()) ? user.getName() : user.getUsername());
        });*/
        saveBatch(importStudents);
        redisTemplate.delete(SystemConstant.EXCEL_IMPORT_REDIS_KEY + seriId);
    }

}
